<script>
import { baseUrl } from '@/config/env';
import { mapGetters } from 'vuex';
import { getDetail, getList } from '@/api/aps/prod';

export default {
  data() {
    return {
      crudForm: {},
      detailForm: {
        title: '销售订单信息',
        no: this.order.no || '',
        client: this.order.client || '',
        quantity: this.order.quantity || '',
        quantityPlanned: this.order.quantityPlaned || 0,
        deliveryDate: this.order.deliveryDate || '',
        productCode: this.order.productCode || '',
      },
      detailOption: {
        span: 22,
        offset: 1,
        submitBtn: false,
        emptyBtn: false,
        menuBtn: false,
        labelWidth: 120,
        column: [
          { label: '销售订单号', prop: 'no', disabled: true },
          { label: '客户名称', prop: 'client', disabled: true },
          { label: '订单数量', prop: 'quantity', disabled: true, append: '件'},
          { label: '已计划数量', prop: 'quantityPlanned', disabled: true, append: '件'},
          { label: '剩余未计划数量', prop: 'quantityLeft', disabled: true, append: '件'},
          { label: '产品代码', prop: 'productCode', disabled: true },
          { label: '最后交期', prop: 'deliveryDate', disabled: true },
        ],
      },
      // 新增生产工单定义表单
      productionForm: {
        title: '生产工单定义',
        workOrderNo: '',
        planQuantity: null,
        planStartDate: '',
        planEndDate: '',
      },
      productionOption: {
        labelWidth: 120,
        span: 22,
        offset: 1,
        submitBtn: false,
        emptyBtn: false,
        menuBtn: false,
        column: [
          {
            label: '生产工单号',
            prop: 'workOrderNo',
            disabled: true,
          },
          {
            label: '计划生产数量',
            prop: 'planQuantity',
            // type: 'number',
            // suffix: '件',
            append: 'KG',
            align: 'right',
            controls: false,
          },
          {
            label: '计划开始时间',
            prop: 'planStartDate',
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
          },
          {
            label: '计划结束时间',
            prop: 'planEndDate',
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            rules: [
              {
                validator: this.validateEndDate,
                trigger: 'change',
              },
            ],
          },
        ],
      },
      query: {
        orderNo: this.order.no,
      },
      search: {},
      loading: true,
      page: {
        pageSize: 5,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      crudOption: {
        height: 'auto',
        calcHeight: 210,
        searchShow: false,
        searchMenuSpan: 24,
        tip: false,
        border: true,
        index: false,
        addBtn: false,
        viewBtn: true,
        selection: false,
        searchSpan: 24,
        column: [
          {
            label: '生产工单号',
            prop: 'prodId',
          },
          {
            label: '计划量',
            prop: 'planed',
          },
          {
            label: '完成量',
            prop: 'menufactured',
          },
          {
            label: '计划开始时间',
            prop: 'startDate',
          },
          {
            label: '计划结束时间',
            prop: 'endDate',
          },
          {
            label: '实际开始时间',
            prop: 'actualStartDate',
            type: 'datetime',
          },
          {
            label: '实际结束时间',
            prop: 'actualEndDate',
            type: 'datetime',
          },
          {
            label: '状态',
            type: 'select',
            dicUrl: baseUrl + '/blade-system/dict/dictionary?code=order_state',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            slot: true,
            prop: 'state',
          },
          {
            label: '模式',
            type: 'select',
            dicUrl: baseUrl + '/blade-system/dict/dictionary?code=order_mode',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            slot: true,
            prop: 'mode',
          },
        ],
        menu: false,
      },
      data: [],
    };
  },
  mounted() {
    // 初始化生产工单号
    this.productionForm.workOrderNo = this.generateWorkOrderNo();
  },
  watch: {
    order: {
      immediate: true,
      deep: true,
      handler(val) {
        this.detailForm = {
          no: (val && val.no) || '',
          client: (val && val.client) || '',
          quantity: (val && val.quantity) || '',
          deliveryDate: (val && val.deliveryDate) || '',
          productCode: (val && val.productCode) || '',
        };
      },
    },
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.order_add, false),
        viewBtn: this.validData(this.permission.order_view, false),
        delBtn: this.validData(this.permission.order_delete, false),
        editBtn: this.validData(this.permission.order_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  methods: {
    // 生成生产工单号
    generateWorkOrderNo() {
      const randomNum = Math.floor(Math.random() * 900000000) + 100000000; // 9位随机数字
      const suffix = Math.floor(Math.random() * 90) + 10; // 2位随机数字
      return `${randomNum}W${suffix}`;
    },
    // 验证结束时间
    validateEndDate(rule, value, callback) {
      if (!value && !this.productionForm.planStartDate) {
        callback();
        return;
      }
      if (value && this.productionForm.planStartDate) {
        const startDate = new Date(this.productionForm.planStartDate);
        const endDate = new Date(value);
        if (endDate <= startDate) {
          callback(new Error('计划结束时间必须晚于计划开始时间'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.crudForm.id).then(res => {
          this.crudForm = res.data.data;
        });
      }
      // done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      // done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    },
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    order: {
      type: Object,
      default: {},
    },
  },
};
</script>

<template>
  <basic-container>
    <el-dialog
      v-model="this.dialogVisible"
      title="创建生产工单"
      width="90%"
      @open="searchChange({ orderNo: this.order.no })"
      @close="$emit('closeDialog', {})"
    >
      <div class="dialog-container">
        <el-row :gutter="20" class="form-row">
          <el-col :span="12">
            <div class="form-container">
              <avue-form :option="detailOption" v-model="detailForm"></avue-form>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="form-container">
              <avue-form :option="productionOption" v-model="productionForm"></avue-form>
            </div>
          </el-col>
        </el-row>
        <el-row class="table-row">
          <avue-crud
            :option="crudOption"
            :table-loading="loading"
            :data="data"
            :permission="permissionList"
            :before-open="beforeOpen"
            v-model="crudForm"
            v-model:search="search"
            v-model:page="page"
            ref="prodCrud"
            @search-change="searchChange"
            @search-reset="searchReset"
            @selection-change="selectionChange"
            @current-change="currentChange"
            @size-change="sizeChange"
            @on-load="onLoad"
          >
          </avue-crud>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false"> 确定</el-button>
        </div>
      </template>
    </el-dialog>
  </basic-container>
</template>

<style scoped lang="scss">
.form-container {
  border-radius: 4px;
  padding: 16px;
  min-height: 200px;
  height: 100%;
  background-color: #e8e8e8;

  .avue-form {
    :deep {
      --el-fill-color-blank: 'transparent';
      --el-border-color-lighter: 'transparent';
    }

    :deep(.el-input) {
      --el-fill-color-blank: #ffffff; // 恢复为白色或其他你想要的值
    }
  }
}
</style>
